package com.dongdongshop.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradeFastpayRefundQueryRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeFastpayRefundQueryResponse;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.dongdongshop.data.Result;
import com.dongdongshop.vo.AlipayQueryRefund;
import com.dongdongshop.vo.AlipayTradeRefund;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Objects;


@Controller
@RequestMapping("aliPay")
public class AliPayController {

    @Autowired
    private AlipayClient alipayClient;

    //支付
    @PostMapping("tradePay")
    @ResponseBody
    public String tradePay(String out_trade_no,String total_amount ,String subject ) throws AlipayApiException {
//        AlipayClient alipayClient = new DefaultAlipayClient(serverUrl, appId,publicKey, format,charset,privateKey,signType);

        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        // TODO 我们提供的异步回调接口 : 支付宝通知我们的接口,支付是否成功
        request.setNotifyUrl("http://2330076e.r7.cpolar.top/aliPayCallback/notifyUrl");
        // TODO 同步回调接口 : 让用户从付款页面调回我们的页面
        request.setReturnUrl("http://2330076e.r7.cpolar.top/aliPayCallback/returnUrl");
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", out_trade_no);
        bizContent.put("total_amount", total_amount);
        bizContent.put("subject", subject);
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
        //bizContent.put("time_expire", "2022-08-01 22:00:00");

        //// 商品明细信息，按需传入
        //JSONArray goodsDetail = new JSONArray();
        //JSONObject goods1 = new JSONObject();
        //goods1.put("goods_id", "goodsNo1");
        //goods1.put("goods_name", "子商品1");
        //goods1.put("quantity", 1);
        //goods1.put("price", 0.01);
        //goodsDetail.add(goods1);
        //bizContent.put("goods_detail", goodsDetail);

        //// 扩展信息，按需传入
        //JSONObject extendParams = new JSONObject();
        //extendParams.put("sys_service_provider_id", "2088511833207846");
        //bizContent.put("extend_params", extendParams);

        request.setBizContent(bizContent.toString());
        AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        return response.getBody();
    }


    //查询交易
    @PostMapping("queryTrade")
    @ResponseBody
    public Result queryTrade(String out_trade_no){
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", out_trade_no);
//bizContent.put("trade_no", "2014112611001004680073956707");
        request.setBizContent(bizContent.toString());
        AlipayTradeQueryResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return Result.ER();
        }
        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        String body = response.getBody();//查询出来的结果
        JSONObject json = JSONObject.parseObject(body);
        System.out.println(json);
        return Result.OK().setData(json);
    }

    //退款
    @PostMapping("tradeRefund")
    @ResponseBody
    public Result tradeRefund(@RequestParam String trade_no,@RequestParam String refund_amount,@RequestParam String out_request_no){
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("trade_no", trade_no);
        bizContent.put("refund_amount", refund_amount);
        bizContent.put("out_request_no", out_request_no);

        // 返回参数选项，按需传入
        //JSONArray queryOptions = new JSONArray();
        //queryOptions.add("refund_detail_item_list");
        //bizContent.put("query_options", queryOptions);

        request.setBizContent(bizContent.toString());
        AlipayTradeRefundResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return Result.ER();
        }
        if(response.isSuccess()){
            System.out.println("调用成功");
            String body = response.getBody();
            JSONObject jsonObject = JSONObject.parseObject(body);
            AlipayTradeRefund refund = JSONObject.parseObject(JSONObject.toJSONString(jsonObject.get("alipay_trade_refund_response")), AlipayTradeRefund.class);
            if (!Objects.equals(refund.getFund_change(),"Y")){
                //退款原因 : 重复退款  2 : 失败
                //查询退款
                AlipayQueryRefund alipayTradeRefund = queryRefund(trade_no, out_request_no);
                if (alipayTradeRefund == null){
                    return Result.ER().setData("退款失败");
                }
                if (!Objects.equals("REFUND_SUCCESS",alipayTradeRefund.getRefund_status())){
                    return Result.ER().setData("退款失败");
                }
                return Result.OK().setData("已经退款");
            }
            return Result.OK().setData("退款成功");
        } else {
            System.out.println("调用失败");
            return Result.ER().setData("退款失败");
        }
    }

    //退款查询
    private AlipayQueryRefund queryRefund(String trade_no, String out_request_no){
        AlipayTradeFastpayRefundQueryRequest request = new AlipayTradeFastpayRefundQueryRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("trade_no", trade_no);
        bizContent.put("out_request_no",out_request_no);

        request.setBizContent(bizContent.toString());
        AlipayTradeFastpayRefundQueryResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return null;
        }
        if(response.isSuccess()){
            System.out.println("调用成功");
            String body = response.getBody();
            JSONObject jsonObject = JSONObject.parseObject(body);
            AlipayQueryRefund trad = JSONObject.parseObject(JSONObject.toJSONString(jsonObject.get("alipay_trade_fastpay_refund_query_response")), AlipayQueryRefund.class);
            return trad;
        } else {
            System.out.println("调用失败");
            return null;
        }
    }
}
